//
//  ViewController.m
//  socketClent
//
//  Created by lanou on 16/7/21.
//  Copyright © 2016年 lhk. All rights reserved.
//

#import "ViewController.h"
#import "GCDAsyncSocket.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,GCDAsyncSocketDelegate>
@property (weak, nonatomic) IBOutlet UITextField *textContent;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)GCDAsyncSocket *clientSock;
@property(nonatomic,strong)NSMutableArray *datas;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.tableView.rowHeight = 50;
    [self.clientSock connectToHost:@"127.0.0.1" onPort:5200 error:nil];
    [self.clientSock readDataWithTimeout:-1 tag:0];
}

-(GCDAsyncSocket *)clientSock{
    if (_clientSock==nil) {
        _clientSock = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];
    }
    return _clientSock;
}
-(NSMutableArray *)datas{
    if (_datas == nil) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}
- (IBAction)senderContent {
    
    [self.clientSock writeData:[self.textContent.text dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datas.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text = @"1";
    cell.detailTextLabel.text = self.datas[indexPath.row];
    return  cell;
}

-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    
}
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
   
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.datas addObject:str];
        [self.tableView reloadData];
    });
    [sock readDataWithTimeout:-1 tag:0];
    
}
@end
